//
//  LZRestaurantInfoViewController.m
//  laziz_Merchant
//
//  Created by ZhaoDongBo on 2016/12/15.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZRestaurantInfoViewController.h"
#import "LZEditGroupOrderViewController.h"
#import "LZMyRestaurantInfoTableView.h"
#import "LZMyRestaurantInfoHeaderView.h"

#import "UINavigationBar+BackgroundColor.h"
#import "UIViewController+NavigationItemSetting.h"

#import "LZSelectDateView.h"

#import "Masonry.h"

#import "GVUserDefaults+LZProperties.h"

#import "LZUserModel.h"
#import "MJExtension.h"
#import "LZGroupItemModel.h"
#import "LZUserInfoPresenter.h"
#import "LZMapModel.h"
#import "LZMapViewController.h"
#import "LZRemindView.h"


@interface LZRestaurantInfoViewController () <LZMyRestaurantInfoHeaderViewDelegate, LZEditGroupOrderViewControllerDelegate>

@property (nonatomic, strong) LZMyRestaurantInfoTableView * tableView;
@property (nonatomic, strong) LZSelectDateView * selectTimeView;

@property (nonatomic, strong) UIButton *nav_right_save;

@property (nonatomic, strong) LZUserInfoPresenter * userInfoPresenter;
@property (nonatomic, strong) LZCurrentUserInfo * userInfoModel;
@property (nonatomic, strong) LZMerchantInfoModel * merchantInfoModel;

@property (nonatomic, strong) __block NSMutableArray * dataArray;

@end

@implementation LZRestaurantInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"餐厅信息页面";
    self.title = LZLocalizedString(@"restaurant_info", nil);
    self.view.backgroundColor = UIColorFromRGB(0xf9f7f7, 1);
    
    self.dataArray = [NSMutableArray array];
    self.userInfoPresenter = [[LZUserInfoPresenter alloc] init];
    
    self.userInfoModel = [LZUserModel Instance].userInfo;
    self.merchantInfoModel = [LZUserModel Instance].merchantInfo;
    
    WS(weakSelf);
    //获取团购商品列表
    [self.userInfoPresenter userGetGrouponListSuccess:^(id data) {
        DLog(@"获取团购商品列表：%@", data);
        NSMutableArray * tempArray = [data objectForKey:@"data"];
        for (int i = 0; i < tempArray.count; i++) {
            LZGroupItemModel * model = [LZGroupItemModel mj_objectWithKeyValues:tempArray[i]];
            if (model) {
                [weakSelf.dataArray addObject:model];
            }
        }
        
        weakSelf.tableView.groupListArrays = [weakSelf.dataArray mutableCopy];
        [weakSelf.tableView reloadData];
        
    } onFail:^(NSString *fail) {
        DLog(@"获取团购商品列表：%@", fail);
    }];
    
    [self configNavigationButton];
    [self configViews];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.tableView reloadData];
}

- (void)configViews {
    [self.view addSubview:self.tableView];
    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
}

- (void)configNavigationButton {
    
    self.nav_right_save = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nav_right_save.frame = CGRectMake(0, 0, 40, 40);
    self.nav_right_save.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.nav_right_save setTitle:LZLocalizedString(@"save", @"") forState:UIControlStateNormal];
    [self.nav_right_save setTitleColor:UIColorFromRGB(0x666666, 1) forState:UIControlStateNormal];
    [self.nav_right_save addTarget:self action:@selector(navbarSaveButtonClickAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self navigationItemSetting:@[self.nav_right_save] type:NAVIGATIONITEMSETTING_RIGHT];
}

- (void)navbarSaveButtonClickAction:(UIButton*)sender {
    
    NSMutableDictionary * param = [NSMutableDictionary dictionary];
    [param setObject:self.userInfoModel.token forKey:@"token"];
    [param setObject:[GVUserDefaults standardUserDefaults].sellerId forKey:@"id"];
    [param setObject:self.merchantInfoModel.openTime forKey:@"openTime"];
    [param setObject:self.merchantInfoModel.closeTime forKey:@"closeTime"];
    [param setObject:[NSNumber numberWithFloat:self.merchantInfoModel.averageConsumption] forKey:@"averageConsumption"];
    
    NSMutableArray * tempArray = [NSMutableArray array];
    for (LZGroupItemModel * item in self.dataArray) {
        NSMutableDictionary * tempDict = [NSMutableDictionary dictionary];
        [tempDict setObject:item.foodName forKey:@"foodName"];
        [tempDict setObject:[NSNumber numberWithFloat:item.foodPrice] forKey:@"foodPrice"];
        [tempArray addObject:tempDict];
    }
    
    [param setObject:tempArray forKey:@"grouponContent"];
    
    [self startLoadingViewForView:self.view loadingViewUserInteractionEnabled:YES];
    
    WS(weakSelf);
    //修改商户资料
    [self.userInfoPresenter userModifyMerchantInfoDict:param onSuccess:^(id data) {
        
        [weakSelf stopLoadingViewForView:weakSelf.view];
        
        DLog(@"修改商户资料：%@", data);
        //更新数据库数据
//        [[LZDatabase dataManager] updateBySellerId:weakSelf.merchantInfoModel.merchantId
//                                       andOpenTime:weakSelf.merchantInfoModel.openTime
//                                      andCloseTime:weakSelf.merchantInfoModel.closeTime
//                                  andAverageConsum:weakSelf.merchantInfoModel.averageConsumption];
        
        [LZRemindView initWithImage:[UIImage imageNamed:@"提示对勾"] andContent:LZLocalizedString(@"save_success", @"")];
        
        weakSelf.nav_right_save.enabled = NO;
        [weakSelf.nav_right_save setTitleColor:UIColorFromRGB(0x666666, 1) forState:UIControlStateNormal];
    } onFail:^(NSString *fail) {
        
        [weakSelf stopLoadingViewForView:weakSelf.view];
        DLog(@"修改商户资料：%@", fail);
    }];
}

- (LZMyRestaurantInfoTableView *)tableView {
    
    WS(weakSelf);
    if (_tableView == nil) {
        _tableView = [[LZMyRestaurantInfoTableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.headerView.delegate = self;
        _tableView.merchantInfoModel = self.merchantInfoModel;
        _tableView.didSelectRowBlock = ^(NSIndexPath * indexPath) {
            if (indexPath.section == 0 && indexPath.row == 3) {
                if ([weakSelf.merchantInfoModel.mapLocationLatitude doubleValue] > 0 && [weakSelf.merchantInfoModel.mapLocationLongitude doubleValue] > 0) {
                    DLog(@"跳转地图");
                    LZMapModel * mapModel = [[LZMapModel alloc] init];
                    mapModel.latitude = [weakSelf.merchantInfoModel.mapLocationLatitude doubleValue];
                    mapModel.longitude = [weakSelf.merchantInfoModel.mapLocationLongitude doubleValue];
                    mapModel.title = weakSelf.merchantInfoModel.restaurantName;
                    mapModel.content = weakSelf.merchantInfoModel.restaurantAddress;
                    
                    LZMapViewController * vc = [[LZMapViewController alloc] init];
                    vc.restaurantModel = mapModel;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }
            }
        };
        
        //营业时间
        _tableView.tapGRActionBlock = ^(NSIndexPath *indexPath, id sender) {
            UIView * v = (UIView *)sender;

            if (v.tag == 1000) {
                [weakSelf.selectTimeView showTimeView:weakSelf.merchantInfoModel.openTime andTimeType:SELECT_TIME_TYPE_Start];
            }
            else {
                [weakSelf.selectTimeView showTimeView:weakSelf.merchantInfoModel.closeTime andTimeType:SELECT_TIME_TYPE_End];
            }
            
            weakSelf.selectTimeView.selectValueBlock = ^(NSString * value) {
                if (v.tag == 1000) { //startlabel
                    weakSelf.merchantInfoModel.openTime = value;
                }
                else { //endlabel
                    weakSelf.merchantInfoModel.closeTime = value;
                }
                
                weakSelf.tableView.merchantInfoModel = weakSelf.merchantInfoModel;
                [weakSelf.tableView reloadData];
                
                [weakSelf.nav_right_save setTitleColor:UIColorFromRGB(0xffffff, 1) forState:UIControlStateNormal];
                weakSelf.nav_right_save.enabled = YES;
                
            };
        };
        
        //人均消费
        _tableView.textFieldEditDidEndBlock = ^(float value) {
            weakSelf.merchantInfoModel.averageConsumption = value;
            weakSelf.tableView.merchantInfoModel = weakSelf.merchantInfoModel;
            [weakSelf.tableView reloadData];
            
            [weakSelf.nav_right_save setTitleColor:UIColorFromRGB(0xffffff, 1) forState:UIControlStateNormal];
            weakSelf.nav_right_save.enabled = YES;
            
        };
        
        //编辑
        _tableView.didEditSelectRowBlock = ^(NSIndexPath * indexPath) {
            
            LZGroupItemModel * model = weakSelf.dataArray[indexPath.row];
            LZEditGroupOrderViewController * vc = [[LZEditGroupOrderViewController alloc] init];
            vc.groupItemModel = model;
            vc.delegate = weakSelf;
            [weakSelf.navigationController pushViewController:vc animated:YES];
            
            [weakSelf.nav_right_save setTitleColor:UIColorFromRGB(0xffffff, 1) forState:UIControlStateNormal];
            weakSelf.nav_right_save.enabled = YES;
            
        };
        
        //删除
        _tableView.didDeleteSelectRowBlock = ^(NSIndexPath * indexPath) {
            
            [weakSelf.nav_right_save setTitleColor:UIColorFromRGB(0xffffff, 1) forState:UIControlStateNormal];
            weakSelf.nav_right_save.enabled = YES;
            
            LZGroupItemModel * model = weakSelf.dataArray[indexPath.row];
            [weakSelf.dataArray removeObject:model];
            
            weakSelf.tableView.groupListArrays = [weakSelf.dataArray copy];
            [weakSelf.tableView reloadData];
            
            
        };
    }
    
    return _tableView;
}

- (LZSelectDateView *)selectTimeView {
    if (_selectTimeView == nil) {
        _selectTimeView = [[LZSelectDateView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) andSelectType:SELECT_TYPE_TIME];
    }
    return _selectTimeView;
}

#pragma mark - LZMyRestaurantInfoHeaderViewDelegate
- (void)tapHeaderViewAddGroupOrderAction {
    LZEditGroupOrderViewController * vc = [[LZEditGroupOrderViewController alloc] init];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - LZEditGroupOrderViewControllerDelegate
//编辑
- (void)editGroupItem:(LZGroupItemModel *)model {
    
    [self.nav_right_save setTitleColor:UIColorFromRGB(0xffffff, 1) forState:UIControlStateNormal];
    
    for (LZGroupItemModel * tempModel in self.dataArray) {
        if ([tempModel.groupItemId isEqualToString:model.groupItemId] ) {
            tempModel.foodName = model.foodName;
            tempModel.foodPrice = model.foodPrice;
            return;
        }
    }
    self.tableView.groupListArrays = [self.dataArray copy];
}
//增加
- (void)addGroupItem:(NSString *)name andPrict:(float)price {
    
    [self.nav_right_save setTitleColor:UIColorFromRGB(0xffffff, 1) forState:UIControlStateNormal];
    
    LZGroupItemModel * model = [[LZGroupItemModel alloc] init];
    model.foodName = name;
    model.foodPrice = price;
    [self.dataArray addObject:model];
    self.tableView.groupListArrays = [self.dataArray copy];
}

@end
